package cn.com.cym.gamezao.web.single;

import cn.com.cym.gamezao.annotation.AccessLimit;
import cn.com.cym.gamezao.annotation.AuthToken;
import cn.com.cym.gamezao.base.BaseController;
import cn.com.cym.gamezao.base.BaseService;
import cn.com.cym.gamezao.base.ResultResponse;
import cn.com.cym.gamezao.base.SearchPage;
import cn.com.cym.gamezao.entity.Sms;
import cn.com.cym.gamezao.entity.single.VaccineReg;
import cn.com.cym.gamezao.service.SmsService;
import cn.com.cym.gamezao.service.single.VaccineRegService;
import cn.com.cym.gamezao.util.CommonUtils;
import cn.com.cym.gamezao.util.SMSUtils;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalField;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "VaccineReg")
@RestController
@RequestMapping(value = "vaccineReg")
@AuthToken(rule = "single.vaccineReg")
public class VaccineRegController extends BaseController<VaccineReg> {

    Logger logger = LoggerFactory.getLogger(getClass());

    final VaccineRegService thisService;
    final SmsService smsService;
    final HttpServletRequest request;
    final EntityManager entityManager;

    public VaccineRegController(VaccineRegService vaccineRegService,HttpServletRequest request, SmsService smsService,EntityManager entityManager){
        this.thisService=vaccineRegService;
        this.request = request;
        this.smsService = smsService;
        this.entityManager = entityManager;
    }

    @Override
    public BaseService<VaccineReg> getService() {
        return this.thisService;
    }

    @ApiImplicitParam(name = "vaccineReg", value = "vaccineReg", required = true,dataType = "VaccineReg")
    @ApiOperation(value = "新建")
    @ApiOperationSupport(order = 1, author = "mr.chen")
    @PostMapping()
    @AuthToken(rule = "add")
    public ResponseEntity<?> add(@RequestBody VaccineReg vaccineReg){
        final VaccineReg vaccineRegStore = this.thisService.save(vaccineReg);
        return ResponseEntity.ok(vaccineRegStore);
    }

    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "id",paramType = "path", required = true,dataType = "Long"),
            @ApiImplicitParam(name = "vaccineReg", value = "vaccineReg", required = true,dataType = "VaccineReg")})
    @ApiOperation(value = "更新")
    @ApiOperationSupport(order = 3, author = "mr.chen")
    @PutMapping("/{id}")
    @AuthToken(rule = "update")
    public ResponseEntity<?> update(@RequestBody VaccineReg vaccineReg,@PathVariable Long id){
        final VaccineReg vaccineRegStore = this.thisService.update(vaccineReg,id);
        return ResponseEntity.ok(vaccineRegStore);
    }

    @ApiImplicitParam(name = "vaccineReg", value = "vaccineReg", required = true,dataType = "VaccineReg")
    @ApiOperation(value = "预约")
    @ApiOperationSupport(order = 4, author = "mr.chen")
    @AccessLimit(limitCount = 5,dateRange = 60*1000L)
    @PostMapping("apply")
    public ResponseEntity<?> apply(@RequestBody VaccineReg vaccineReg) throws IOException {
        VaccineReg apply = this.thisService.apply(vaccineReg);
        /*【厦大翔安医院】您已成功预约HPV疫苗接种，请于2022年9月5日8:00-11:00，携带身份证、社保卡，凭本手机及收到的信息，到门诊二楼疫苗接种处办理手续。如逾期将自动取消预约！温馨提示:如有接种其他疫苗请间隔15天才能接种，若您已接种请忽略此信息。本信息禁止转让。谢谢！*/
        final Sms sms = this.smsService.getAll().get(0);
        SMSUtils.sendMsg(entityManager,sms,apply.getTelNo(),"您（"+vaccineReg.getUserName()+":"+vaccineReg.getCertificateCode()+"）已成功登记HPV疫苗接种,如有疫苗，我们将会短信通知个人，请随时关注个人手机信息",true);
        return ResponseEntity.ok(apply);
    }

    /**
     * 发送消息
     * @param ids ids
     * @return ?
     */
    @PutMapping("sendSms/{arriveDate}")
    @AuthToken(rule = "sendSms")
    public ResponseEntity<?> sendSms(@RequestBody List<Long> ids,@PathVariable("arriveDate") String arriveDate){
        //TODO
        /*【厦大翔安医院】您已成功预约HPV疫苗接种，请于2022年9月5日8:00-11:00，携带身份证、社保卡，凭本手机及收到的信息，到门诊二楼疫苗接种处办理手续。如逾期将自动取消预约！温馨提示:如有接种其他疫苗请间隔15天才能接种，若您已接种请忽略此信息。本信息禁止转让。谢谢！*/

        final Sms sms = this.smsService.getAll().get(0);

        for(Long id: ids){
            final VaccineReg vaccineReg = this.thisService.fetchOne(id);
            String sb ="您("+vaccineReg.getUserName()+":"+vaccineReg.getCertificateCode()+")已成功预约HPV疫苗接种，请于"+arriveDate+" 8:00-11:00，携带身份证、社保卡，凭本手机及收到的信息，到门诊二楼疫苗接种处办理手续。如逾期则一个月后方可重新预约登记。温馨提示:如有接种其他疫苗请间隔15天才能接种，若您已接种请忽略此信息。本信息禁止转让。谢谢！";
            try{
                SMSUtils.sendMsg(entityManager,sms,vaccineReg.getTelNo(),sb,true);
                vaccineReg.setRegStatus("1");
                vaccineReg.setNoticeDateTime(LocalDateTime.now());
                thisService.save(vaccineReg);
            }catch (IOException e){
                logger.error(vaccineReg.getUserName()+"("+vaccineReg.getCertificateCode()+"),发送短信失败！！！！");
            }
        }
        return ResponseEntity.ok(new ResultResponse("已发送短信，请刷新显示",200));
    }

    /**
     * 导出
     * @params startDate s
     * @return ？
     * @throws FileNotFoundException
     */
    @ApiImplicitParam(name = "searchPage", value = "searchPage", required = true,dataType = "SearchPage")
    @ApiOperation(value = "导出")
    @ApiOperationSupport(order = 6, author = "mr.chen")
    // @AuthToken(rule = "exportData")
    @GetMapping(value = "exportData/{startDate}/{endDate}/{vaccine}",produces= {MediaType.APPLICATION_OCTET_STREAM_VALUE})
    public void /*ResponseEntity<?>*/ exportData(@PathVariable("startDate") String startDate,@PathVariable("endDate") String endDate,@PathVariable("vaccine") String vaccine, HttpServletResponse response) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        List<VaccineReg> list = this.thisService.getAllBySearchParams(startDate,endDate,vaccine);
        //InputStream inputStream = new FileInputStream(new File(LocalDateTime.now().getLong(ChronoField.MICRO_OF_SECOND)+".xlsx"));
        // 通过工具类创建writer
        String  aLong = CommonUtils.customIp(request) + LocalDateTime.now().getLong(ChronoField.MICRO_OF_SECOND)+".xlsx";

        ExcelWriter writer = ExcelUtil.getWriter(CommonUtils.filePath(aLong));
        //自定义标题别名
        writer.addHeaderAlias("createTime", "登记时间");
        writer.setColumnWidth(0,30);
        writer.addHeaderAlias("userName", "姓名");
        writer.addHeaderAlias("certificateCode", "证件号");
        writer.setColumnWidth(2,30);
        writer.addHeaderAlias("sex", "性别");
        writer.addHeaderAlias("age", "年龄");
        writer.addHeaderAlias("area", "区域");
        writer.addHeaderAlias("vaccine", "疫苗");
        writer.setColumnWidth(6,30);
        writer.addHeaderAlias("telNo", "联系方式");
        writer.addHeaderAlias("regStatus", "状态");
        writer.addHeaderAlias("noticeDateTime", "通知时间");
        writer.setColumnWidth(9,30);


        headers.setContentDisposition(ContentDisposition.attachment()
                .filename(aLong)
                .build());
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        writer.setOnlyAlias(true);

        list.stream().forEach(vaccineReg -> {
            vaccineReg.setSex("0".equals(vaccineReg.getSex()) ? "男" : "女");
            if("0".equals(vaccineReg.getVaccine())){
                vaccineReg.setVaccine("九价HPV疫苗(19-26岁)");
            }else if("1".equals(vaccineReg.getVaccine())){
                vaccineReg.setVaccine("四价HPV疫苗（26-45岁）");
            }else if("2".equals(vaccineReg.getVaccine())){
                vaccineReg.setVaccine("23价肺炎疫苗(18岁及以上)");
            }else if("3".equals(vaccineReg.getVaccine())){
                vaccineReg.setVaccine("20ug重组乙肝疫苗(18岁及以上)");
            }else if("4".equals(vaccineReg.getVaccine())){
                vaccineReg.setVaccine("四价流感疫苗(18岁及以上)");
            }
            // vaccineReg.setVaccine("0".equals(vaccineReg.getVaccine())?"九价HPV疫苗(19-26岁)":"四价HPV疫苗（26-45岁）");
        });

        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+aLong);
        // response.addHeader("Content-Length",String.valueOf(new File(CommonUtils.filePath(aLong)).length()));
        //response.setHeader ("content-type", "text/html;charset=UTF-8");
        ServletOutputStream out=response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
        // return ResponseEntity.ok(response);
    }
}